﻿using CMS.Tool.WebApi.Models;
using Newtonsoft.Json;
using RazorEngine;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;

namespace CodeTool.WebApi.Models
{
    public class YangjiCoder
    {
        public string page_template { get; set; }
        public string page_template_json { get; set; }
        public YangjiCoder()
        {
            var path = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "Template", "Yangji_Template.txt");
            page_template = File.ReadAllText(path);
            var path2 = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "Template", "Yangji_json.json");
            page_template_json = File.ReadAllText(path2);
        }

        public void Builder()
        {
            var json = page_template_json;
            var list = JsonConvert.DeserializeObject<List<PageDataModel>>(json);

            foreach (var i in list)
            {
                var prev = i.index - 1;
                var next = i.index + 1;
                RazorParse(i.index ?? 1, i.date, prev, next, i.content);
            }

        }

        public void RazorParse(int pageIndex, DateTime? date, int? prev, int? next, string content)
        {
            var entity_result = Razor.Parse(page_template, new
            {
                PostData = (date ?? DateTime.Now).ToString("yyyy-MM-dd"),
                PrevIndex = prev,
                NextIndex = next,
                ContentHtml = content
            });//, "page"

            Utils.Save(
                Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "CodeGenerate\\Code\\Yangji", $"detail_{pageIndex}.html")
                , entity_result);
        }

        public class PageDataModel
        {
            public DateTime? date { get; set; }
            public int? index { get; set; }
            public string content { get; set; }
        }
    }
}